package com.ds.system.sys.service;

import com.ds.cluster.ServerNode;
import com.ds.common.JDSException;
import com.ds.common.md5.MD5;
import com.ds.common.org.CtOrg;
import com.ds.common.org.CtOrgAdminManager;
import com.ds.common.org.CtPerson;
import com.ds.common.util.StringUtility;
import com.ds.config.ErrorListResultModel;
import com.ds.config.ErrorResultModel;
import com.ds.config.ResultModel;
import com.ds.config.TreeListResultModel;
import com.ds.enums.db.MethodChinaName;

import com.ds.esd.custom.annotation.CustomAnnotation;
import com.ds.esd.custom.annotation.DialogAnnotation;
import com.ds.esd.custom.annotation.FormViewAnnotation;
import com.ds.esd.custom.annotation.PopTreeViewAnnotation;
import com.ds.esd.custom.api.annotation.APIEventAnnotation;
import com.ds.esd.custom.api.enums.CustomCallBack;
import com.ds.esd.custom.enums.CustomMenuItem;
import com.ds.esd.custom.module.annotation.ModuleAnnotation;
import com.ds.esd.dsm.domain.annotation.NavDomain;
import com.ds.esd.dsm.domain.enums.NavDomainType;
import com.ds.esd.tool.ui.enums.Dock;
import com.ds.jds.core.esb.EsbUtil;
import com.ds.org.Org;
import com.ds.server.JDSServer;
import com.ds.server.SubSystem;
import com.ds.server.ct.CtSubSystem;
import com.ds.server.service.SysWebManager;
import com.ds.system.sys.view.DeparmentTopTree;
import com.ds.system.sys.view.FolderTopTree;
import com.ds.system.sys.view.PersonPopTree;
import com.ds.system.sys.view.system.DevSystemFormView;
import com.ds.vfs.Folder;
import com.ds.vfs.ct.CtVfsFactory;
import com.ds.web.annotation.Aggregation;
import com.ds.web.annotation.AggregationType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@MethodChinaName(cname = "子系统", imageClass = "spafont spa-icon-coin")
@RequestMapping("/system/dev/")
@Aggregation(type = AggregationType.customDomain,sourceClass =DevSystemService.class )
@NavDomain(type = NavDomainType.menu)
public class DevSystemService {

    @RequestMapping(method = RequestMethod.POST, value = "DevSystemInfo")
    @FormViewAnnotation(saveUrl = "updateDevSystemInfo")
    @DialogAnnotation
    @ModuleAnnotation(caption = "编辑服务信息", width = "650", height = "350")
    @APIEventAnnotation(bindMenu = CustomMenuItem.editor)
    @ResponseBody
    public ResultModel<DevSystemFormView> getDevSystemInfo(String sysId) {
        ResultModel<DevSystemFormView> resultModel = new ResultModel<DevSystemFormView>();

        try {
            ServerNode serverNode = JDSServer.getClusterClient().getServerNodeById(sysId);
            DevSystemFormView serviceView = new DevSystemFormView(serverNode);
            resultModel.setData(serviceView);
        } catch (Exception e) {
            e.printStackTrace();
            resultModel = new ErrorResultModel();
            ((ErrorResultModel<DevSystemFormView>) resultModel).setErrdes(e.getMessage());
        }
        return resultModel;
    }


    @MethodChinaName(cname = "添加SAAS用户")
    @RequestMapping(method = RequestMethod.POST, value = "AddSaaSSystem")
    @FormViewAnnotation(saveUrl = "updateDevSystemInfo")
    @DialogAnnotation
    @ModuleAnnotation(caption = "添加SAAS用户", width = "650", height = "300")
    @APIEventAnnotation(isAllform = true, autoRun = true, bindMenu = CustomMenuItem.add)
    @ResponseBody
    public ResultModel<DevSystemFormView> addSaaSSystem() {
        ResultModel<DevSystemFormView> resultModel = new ResultModel<DevSystemFormView>();
        try {
            SubSystem subSystem = new CtSubSystem();
            subSystem.setSysId(UUID.randomUUID().toString());
            subSystem.setName("新建系统");
            Org topOrg = CtOrgAdminManager.getInstance().createTopOrg(subSystem.getSysId(), subSystem.getName());
            subSystem.setAdminId(topOrg.getLeaderId());
            subSystem.setOrgId(topOrg.getOrgId());
            Folder folder = CtVfsFactory.getCtVfsService().getFolderByPath("form/");
            Folder rootFolder = folder.createChildFolder(subSystem.getSysId(), subSystem.getAdminId());
            subSystem.setVfsPath(rootFolder.getPath());
            getSysWebManager().saveSystemInfo(subSystem).get();
            DevSystemFormView serviceView = new DevSystemFormView(subSystem);
            resultModel.setData(serviceView);
        } catch (Exception e) {
            e.printStackTrace();
            resultModel = new ErrorResultModel();
            ((ErrorResultModel<DevSystemFormView>) resultModel).setErrdes(e.getMessage());
        }
        return resultModel;
    }


    @MethodChinaName(cname = "绑定系统机构信息")
    @RequestMapping(value = {"bindOrgSys"}, method = {RequestMethod.GET, RequestMethod.POST})
    @APIEventAnnotation(isAllform = true, callback = {CustomCallBack.Close})
    public @ResponseBody
    ResultModel<Boolean> bindOrgSys(String sysId, String AddOrg2SysTree) {
        ResultModel<Boolean> userStatusInfo = new ResultModel<Boolean>();
        String[] orgIds = new String[]{};
        if (AddOrg2SysTree != null) {
            orgIds = StringUtility.split(AddOrg2SysTree, ";");
            for (String orgId : orgIds) {
                CtSubSystem subSystem = (CtSubSystem) JDSServer.getClusterClient().getSystem(sysId);
                subSystem.setOrgId(orgId);
                try {
                    getSysWebManager().saveSystemInfo(subSystem).get();
                } catch (JDSException e) {
                    e.printStackTrace();
                }
            }
        }
        return userStatusInfo;

    }

    @RequestMapping(value = {"AddOrg2Sys"}, method = {RequestMethod.GET, RequestMethod.POST})
    @CustomAnnotation(dock = Dock.fill)
    @DialogAnnotation
    @PopTreeViewAnnotation(saveUrl = "bindOrgSys")
    @ModuleAnnotation(dynLoad = true, caption = "绑定组织机构", width = "350", height = "400")
    @APIEventAnnotation(isAllform = true, autoRun = true)
    @ResponseBody
    public TreeListResultModel<List<DeparmentTopTree>> addOrg2Sys(String sysId) {
        TreeListResultModel<List<DeparmentTopTree>> result = new TreeListResultModel<List<DeparmentTopTree>>();
        try {
            List<DeparmentTopTree> topTrees = new ArrayList<>();
            topTrees.add(new DeparmentTopTree(""));
            result.setData(topTrees);
        } catch (JDSException e) {
            result = new ErrorListResultModel<>();
            ((ErrorListResultModel) result).setErrcode(e.getErrorCode());
            ((ErrorListResultModel) result).setErrdes(e.getMessage());
        }
        return result;
    }


    @MethodChinaName(cname = "绑定空间")
    @RequestMapping(value = {"bindSpaceSys"}, method = {RequestMethod.GET, RequestMethod.POST})
    @APIEventAnnotation(isAllform = true, callback = {CustomCallBack.Close})
    public @ResponseBody
    ResultModel<Boolean> bindSpaceSys(String sysId, String AddSpace2SysTree) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        String[] folderIds = new String[]{};
        if (AddSpace2SysTree != null) {
            folderIds = StringUtility.split(AddSpace2SysTree, ";");
            for (String folderId : folderIds) {
                try {
                    CtSubSystem subSystem = (CtSubSystem) JDSServer.getClusterClient().getSystem(sysId);
                    Folder folder = CtVfsFactory.getCtVfsService().getFolderById(folderId);
                    subSystem.setVfsPath(folder.getPath());
                    getSysWebManager().saveSystemInfo(subSystem).get();
                } catch (JDSException e) {
                    result = new ErrorResultModel<>();
                    ((ErrorResultModel) result).setErrcode(e.getErrorCode());
                    ((ErrorResultModel) result).setErrdes(e.getMessage());
                }
            }
        }
        return result;

    }


    @RequestMapping(value = {"AddPerson2Sys"}, method = {RequestMethod.GET, RequestMethod.POST})
    @CustomAnnotation(dock = Dock.fill)
    @DialogAnnotation
    @PopTreeViewAnnotation(saveUrl = "bindPersonSys")
    @ModuleAnnotation(dynLoad = true, caption = "绑定管理员账户", width = "350", height = "400")
    @APIEventAnnotation(isAllform = true, autoRun = true)
    @ResponseBody
    public TreeListResultModel<List<PersonPopTree>> addPerson2Sys(String sysId) {
        TreeListResultModel<List<PersonPopTree>> result = new TreeListResultModel<List<PersonPopTree>>();
        List<PersonPopTree> topTrees = new ArrayList<>();
        SubSystem subSystem = JDSServer.getClusterClient().getSystem(sysId.toString());
        try {
            Org org = CtOrgAdminManager.getInstance().getOrgById(subSystem.getOrgId());
            topTrees.add(new PersonPopTree("", org));
        } catch (JDSException e) {
            result = new ErrorListResultModel<>();
            ((ErrorListResultModel) result).setErrcode(e.getErrorCode());
            ((ErrorListResultModel) result).setErrdes(e.getMessage());
        }


        result.setData(topTrees);

        return result;
    }


    @MethodChinaName(cname = "绑定管理员账户")
    @RequestMapping(value = {"bindPersonSys"}, method = {RequestMethod.GET, RequestMethod.POST})
    @APIEventAnnotation(isAllform = true, callback = {CustomCallBack.Close})
    public @ResponseBody
    ResultModel<Boolean> bindPersonSys(String sysId, String AddPerson2SysTree) {
        ResultModel<Boolean> result = new ResultModel<Boolean>();
        String[] personIds = new String[]{};
        if (AddPerson2SysTree != null) {
            personIds = StringUtility.split(AddPerson2SysTree, ";");
            for (String personId : personIds) {
                try {
                    CtSubSystem subSystem = (CtSubSystem) JDSServer.getClusterClient().getSystem(sysId);
                    if (!personId.startsWith("org")) {
                        subSystem.setAdminId(personId);
                    }
                    getSysWebManager().saveSystemInfo(subSystem).get();
                } catch (JDSException e) {
                    result = new ErrorResultModel<>();
                    ((ErrorResultModel) result).setErrcode(e.getErrorCode());
                    ((ErrorResultModel) result).setErrdes(e.getMessage());
                }
            }
        }
        return result;

    }


    @MethodChinaName(cname = "绑定空间")
    @RequestMapping(value = {"AddSpace2Sys"}, method = {RequestMethod.GET, RequestMethod.POST})
    @CustomAnnotation(dock = Dock.fill)
    @PopTreeViewAnnotation(saveUrl = "bindSpaceSys")
    @DialogAnnotation
    @ModuleAnnotation(dynLoad = true, caption = "绑定空间", width = "350", height = "400")
    @APIEventAnnotation(isAllform = true, autoRun = true)
    @ResponseBody
    public TreeListResultModel<List<FolderTopTree>> addSpace2Sys(String sysId) {
        TreeListResultModel<List<FolderTopTree>> result = new TreeListResultModel<List<FolderTopTree>>();
        List<FolderTopTree> topTrees = new ArrayList<>();
        try {
            topTrees.add(new FolderTopTree(""));
        } catch (JDSException e) {
            result = new ErrorListResultModel<>();
            ((ErrorListResultModel) result).setErrcode(e.getErrorCode());
            ((ErrorListResultModel) result).setErrdes(e.getMessage());
        }
        result.setData(topTrees);
        return result;
    }


    ResultModel<Boolean> addSystem(SubSystem subSystem) {
        ResultModel<Boolean> userStatusInfo = new ResultModel<Boolean>();
        try {
            getSysWebManager().saveSystemInfo(subSystem).get();
        } catch (JDSException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        }

        return userStatusInfo;
    }

    @MethodChinaName(cname = "更新系统服务信息")
    @RequestMapping(value = {"updateDevSystemInfo"}, method = {RequestMethod.GET, RequestMethod.POST})
    @APIEventAnnotation(callback = {CustomCallBack.Close}, bindMenu = CustomMenuItem.formSave)
    public @ResponseBody
    ResultModel<Boolean> updateDevSystemInfo(@RequestBody DevSystemFormView subSystem) {
        ResultModel<Boolean> userStatusInfo = new ResultModel<Boolean>();
        try {
            String orgName = subSystem.getOrgname();
            String orgId = subSystem.getOrgId();
            CtOrg topOrg = null;
            if (orgId == null || orgId.equals("")) {
                topOrg = (CtOrg) CtOrgAdminManager.getInstance().createTopOrg(subSystem.getSysId(), orgName);
                subSystem.setOrgId(topOrg.getOrgId());
            } else {
                topOrg = (CtOrg) CtOrgAdminManager.getInstance().getOrgById(orgId);
                if (topOrg == null) {
                    topOrg = (CtOrg) CtOrgAdminManager.getInstance().createTopOrg(subSystem.getSysId(), orgName);
                    subSystem.setOrgId(topOrg.getOrgId());
                } else if (orgName == null || !topOrg.getName().equals(orgName)) {
                    topOrg.setName(orgName);
                    CtOrgAdminManager.getInstance().saveOrg(topOrg);
                }
            }
            String vfsPath = subSystem.getVfsPath();
            if (vfsPath == null || vfsPath.equals("")) {
                Folder folder = CtVfsFactory.getCtVfsService().mkDir("form/" + orgName);
                subSystem.setVfsPath(folder.getPath());
            }
            String personId = subSystem.getAdminId();

            String defaultAdminAccount = subSystem.getPersonname();
            if (!defaultAdminAccount.startsWith(subSystem.getEnname() + "_")) {
                defaultAdminAccount = subSystem.getEnname() + "_" + defaultAdminAccount;
            }
            if (CtOrgAdminManager.getInstance().getPersonByAccount(defaultAdminAccount) != null) {
                defaultAdminAccount = defaultAdminAccount + "_" + StringUtility.createRandom(true, 3);
            }

            CtPerson person = null;
            if (personId == null || personId.equals("")) {
                person = (CtPerson) topOrg.getLeader();
            } else {
                person = (CtPerson) CtOrgAdminManager.getInstance().getPersonById(personId);
            }

            if (person == null) {
                person = (CtPerson) CtOrgAdminManager.getInstance().createPerson(topOrg.getOrgId(), defaultAdminAccount, subSystem.getPersonname());
                CtOrgAdminManager.getInstance().savePerson(person);
                subSystem.setAdminId(person.getID());
            } else {

                if (!defaultAdminAccount.equals(person.getAccount())) {
                    person.setAccount(defaultAdminAccount);
                    person.setName(subSystem.getPersonname());
                    person.setPassword(MD5.getHashString("admin"));
                    CtOrgAdminManager.getInstance().savePerson(person);
                }
            }

            getSysWebManager().saveSystemInfo(subSystem).get();
        } catch (JDSException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        }

        return userStatusInfo;
    }

    @RequestMapping(value = {"deleteSystem"}, method = {RequestMethod.GET, RequestMethod.POST})
    @APIEventAnnotation(callback = {CustomCallBack.Reload}, bindMenu = CustomMenuItem.delete)
    public @ResponseBody
    ResultModel<Boolean> deleteSystem(String systemIds) {
        ResultModel<Boolean> userStatusInfo = new ResultModel<Boolean>();
        try {
            String[] systemIdArr = systemIds.split(";");
            for (String systemId : systemIdArr) {
                SubSystem system = getSysWebManager().getSubSystemInfo(systemId).get();

            }

        } catch (JDSException e) {
            userStatusInfo = new ErrorResultModel();
            ((ErrorResultModel) userStatusInfo).setErrcode(e.getErrorCode());
            ((ErrorResultModel) userStatusInfo).setErrdes(e.getMessage());
        }

        return userStatusInfo;
    }

//    @GridViewAnnotation
//        @MethodChinaName(cname = "获取节点信息")
//        @ModuleAnnotation()
//        @RequestMapping(value = {"AppServerNodeInfo"}, method = {RequestMethod.GET, RequestMethod.POST})
//        public @ResponseBody
//        ResultModel<ServerNodeFormView> getServerNodeInfo(String code) {
//            ServerNode serverNode = JDSServer.getClusterClient().getServerNodeById(code);
//            ResultModel<ServerNodeFormView> userStatusInfo = new ResultModel<ServerNodeFormView>();
//            userStatusInfo.setData(new ServerNodeFormView(serverNode));
//        return userStatusInfo;
//    }


    SysWebManager getSysWebManager() {
        return (SysWebManager) EsbUtil.parExpression("$SysWebManager");
    }

}
